import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

typedef FromJson<T> = T Function(Map<String, dynamic> json);
typedef ToJson<T> = Map<String, dynamic> Function(T object);

/// 支持泛型序列化和反序列化的 SharedPreferences 工具类
class utilSp {
  static final utilSp _instance = utilSp._internal();
  late SharedPreferences _prefs;

  factory utilSp() => _instance;

  utilSp._internal();

  /// 初始化（在 main 中调用一次）
  Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  /// ------------------ 原始类型存储 ------------------

  Future<bool> setString(String key, String value) async =>
      await _prefs.setString(key, value);

  Future<bool> setInt(String key, int value) async =>
      await _prefs.setInt(key, value);

  Future<bool> setDouble(String key, double value) async =>
      await _prefs.setDouble(key, value);

  Future<bool> setBool(String key, bool value) async =>
      await _prefs.setBool(key, value);

  Future<bool> setStringList(String key, List<String> value) async =>
      await _prefs.setStringList(key, value);

  String? getString(String key) => _prefs.getString(key);
  int? getInt(String key) => _prefs.getInt(key);
  double? getDouble(String key) => _prefs.getDouble(key);
  bool? getBool(String key) => _prefs.getBool(key);
  List<String>? getStringList(String key) => _prefs.getStringList(key);

  /// ------------------ 泛型对象存储 ------------------

  /// 存储一个对象
  Future<bool> setObject<T>(String key, T obj, ToJson<T> toJson) async {
    String jsonStr = jsonEncode(toJson(obj));
    return await _prefs.setString(key, jsonStr);
  }

  /// 获取一个对象
  T? getObject<T>(String key, FromJson<T> fromJson) {
    String? jsonStr = _prefs.getString(key);
    if (jsonStr == null) return null;
    return fromJson(jsonDecode(jsonStr));
  }

  /// 存储对象列表
  Future<bool> setObjectList<T>(
      String key, List<T> list, ToJson<T> toJson) async {
    String jsonStr = jsonEncode(list.map((e) => toJson(e)).toList());
    return await _prefs.setString(key, jsonStr);
  }

  /// 获取对象列表
  List<T>? getObjectList<T>(String key, FromJson<T> fromJson) {
    String? jsonStr = _prefs.getString(key);
    if (jsonStr == null) return null;
    List<dynamic> jsonList = jsonDecode(jsonStr);
    return jsonList.map((e) => fromJson(Map<String, dynamic>.from(e))).toList();
  }

  /// ------------------ 删除/清除 ------------------

  Future<bool> remove(String key) async => await _prefs.remove(key);
  Future<bool> clear() async => await _prefs.clear();
}
//----------基本类型---------------
// void exampleString() async {
//   final sp = SPUtil();
//
//   // 存储字符串
//   await sp.setString('username', 'flutter_dev');
//
//   // 读取字符串
//   String? username = sp.getString('username');
//
//   print('用户名：$username'); // 输出：用户名：flutter_dev
// }

/// ------------------ 存储对象 ------------------
// class User {
//   String name;
//   int age;
//
//   User({required this.name, required this.age});
//
//   // JSON 转对象
//   factory User.fromJson(Map<String, dynamic> json) =>
//       User(name: json['name'], age: json['age']);
//
//   // 对象转 JSON
//   Map<String, dynamic> toJson() => {
//     'name': name,
//     'age': age,
//   };
// }
//
// void saveUser() async {
//   final sp = SPUtil();
//   User user = User(name: 'Tom', age: 28);
//
//   await sp.setObject<User>('user', user, (u) => u.toJson());
// }
//
// void loadUser() {
//   final sp = SPUtil();
//   User? user = sp.getObject<User>('user', (json) => User.fromJson(json));
//   if (user != null) {
//     print('用户名: ${user.name}, 年龄: ${user.age}');
//   }
// }